using System;
using System.Collections;
using System.Data;

namespace NimblePros.SimpleCms
{
	/// <summary>
	/// Summary description for Duplicates.
	/// </summary>
	public class Duplicates
	{
		private Duplicates()
		{
		}

		/// <summary>
		/// Removes duplicate rows from given DataTable
		/// </summary>
		/// <param name="tbl">Table to scan for duplicate rows</param>
		/// <param name="KeyColumns">An array of DataColumns 
		///   containing the columns to match for duplicates</param>
		public static void RemoveDuplicates(DataTable tbl, 
			DataColumn[] keyColumns)
		{
			int rowNdx = 0;
			while(rowNdx < tbl.Rows.Count-1)
			{
				DataRow[] dups = FindDups(tbl, rowNdx, keyColumns);
				if(dups.Length>0)
				{
					foreach(DataRow dup in dups)
					{
						tbl.Rows.Remove(dup);
					}
				}
				else
				{
					rowNdx++;
				}
			}
		}
 
		private static DataRow[] FindDups(DataTable tbl, int sourceNdx, DataColumn[] keyColumns)
		{
			ArrayList retVal = new ArrayList();
 
			DataRow sourceRow = tbl.Rows[sourceNdx];
			for(int i=sourceNdx + 1; i<tbl.Rows.Count; i++)
			{
				DataRow targetRow = tbl.Rows[i];
				if(IsDup(sourceRow, targetRow, keyColumns))
				{
					retVal.Add(targetRow);
				}
			}
			return (DataRow[]) retVal.ToArray(typeof(DataRow));
		} 
 
		private static bool IsDup(DataRow sourceRow, 
			DataRow targetRow, 
			DataColumn[] keyColumns)
		{
			bool retVal = true;
			foreach(DataColumn column in keyColumns)
			{
				retVal = retVal && sourceRow[column].Equals(targetRow[column]);
				if(!retVal) break;
			}
			return retVal;
		}
 
		public static void ConsolePrintRows(DataTable tbl)
		{
			for(int i=0; i<tbl.Rows.Count; i++)
			{
				Console.WriteLine("row: {0}, ColumnA: {1}, ColumnB: {2}", i, tbl.Rows[i]["ColumnA"], tbl.Rows[i]["ColumnB"]);
			}
		}

		public static string WebPrintRows(DataTable tbl)
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder(500);
			sb.Append("<table><caption>");
			sb.Append(tbl.TableName);
			sb.Append("</caption>");
			for(int i=0; i<tbl.Rows.Count; i++)
			{
				sb.Append("<tr>");
				for(int j=0; j< tbl.Columns.Count; j++)
				{
					sb.Append("<td>");
					sb.Append(tbl.Rows[i][j].ToString());
					sb.Append("</td>");
				}
				sb.Append("</tr>");
			}
			sb.Append("</table>");
			return sb.ToString();
		}
	}
}
